<template>
  <div id="DemoPage">
    <h1>RY-EDIT-TABLE</h1>
    <div class="header" style="display: flex;flex-direction: column; height: 50px;">
      <div class="group-1" style="display: flex;height:40px; justify-content: flex-end;padding: 10px; padding-right:0">
        <el-button type="success" @click="insert()">新增</el-button>
        <el-button type="success" @click="bachDelete()">批量删除</el-button>
        <el-button type="success" @click="activateAllRows()">激活全编辑</el-button>
        <el-button type="success" @click="save()">保存全部</el-button>
        <el-button type="success" @click="recoverAll()">还原全部</el-button>
        <!-- <el-button style="margin-right: 10px;" type="success" @click="clearValidateByCell()">清空指定单元格校验信息</el-button>
        <el-input style="width:30px;margin-right:10px" v-model.number="rowIndex" />
        <el-input style="width:80px;margin-right:10px" v-model="cellProp" /> -->

        <el-button type="success" @click="clearValidate()">清空校验信息</el-button>
        <el-button type="success" @click="changeRules()">调整校验规则</el-button>
        <el-button type="success" @click="shuffleListConfig()">调整表头顺序</el-button>
      </div>
      <!-- <div class="group-2" style="display: flex ; justify-content: flex-end; height: 40px;padding: 10px;">
        <el-button type="success" @click="shuffleListConfig()">调整表头顺序</el-button>
      </div> -->
    </div>
    <ry-edit-table
      ref="ryEditTable"
      :listData="listData"
      :listConfig="listConfig"
      :rowButtons="rowButtons"
      :operationsConfig="{ width: 160 }"
      :action="'action'"
      :cellStyle="{ color: 'orange' }"
      :cellClassName="'custom-cell-class'"
   
      trigger="onChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55px" fixed="left" />
      <el-table-column type="index" label="序号" width="100px" fixed="left" />
    </ry-edit-table>
  </div>
</template>

<script>
import { shuffleArray } from "../../packages/utils/index.js";
export default {
  name: "demoPage",

  data() {
    return {
      rowIndex: 1,
      cellProp: "age",
      selections: [],
      dropDownOptions: {
        job: [],
        from: [],
      },
      // 表头配置
      listConfig: [
        {
          mode: "text",
          label: "姓名",
          prop: "name",
          minWidth: "100px",
          disabled(row) {
            return row.name === "cherry" ? true : false;
          },
          change: (v, row, index) => {
            console.log("v, row, index: ", v, row, index);
          },
          blur: (v) => {
            console.log("name blur");
          },
          rules: [
            {
              type: "string",
              required: true,
              message: "姓名不能为空",
            },
            // {
            //   message: "name is not paired",
            //   validator: (rule, value) => value === "muji",
            // },
          ],
        },
        {
          mode: "text",
          label: "年龄",
          prop: "age",
          minWidth: "100px",
          sortable: true,
          change: (v, row) => {
            console.log(row);
            row.job = v <= 22 ? "2" : "";
            if (row.age < 18) row.job = "";
            // this.$refs.ryEditTable.checkByField(row, "job", (valid) => {
            //   console.log(valid ? "job is ok" : "job is not ok");
            // });
            // setTimeout(()=>{
            //   this.$refs.ryEditTable.removeCellError(row,'job')

            // },2000)
            setTimeout(()=>{
              this.$refs.ryEditTable.validateAll((valid,fields)=>{
                console.log('valid,fields: ', valid,fields);

              })

            },2000)
            // setTimeout(()=>{
            //   this.$refs.ryEditTable.removeRowError(row)
            // },6000)
          },
          rules: [
            {
              type: "number",
              asyncValidator: (rule, value) => {
                return new Promise((resolve, reject) => {
                  if (value < 1) {
                    reject("年龄需要1岁"); // reject 这个 error message
                  } else {
                    resolve();
                  }
                });
              },
            },
          ],
        },
        {
          mode: "date",
          label: "出生日期",
          prop: "date",
          minWidth: "150px",
          inputConfig: {
            "value-format": "YYYY-MM-DD",
          },
          rules: [
            {
              type: "date",
              required: true,
              message: "出生日期不能为空",
            },
          ],
        },
        {
          mode: "select",
          label: "职业/身份",
          prop: "job",
          renderProp: "job$view",
          minWidth: "100px",
          placeholder: "请选择",
          inputConfig: {
            clearable: true,
          },
          options: (row) => {
            return row.age > 22
              ? this.dropDownOptions.job.filter((item) => item.value !== "2")
              : this.dropDownOptions.job.filter((item) => item.value === "2");
          },

          rules: [
            {
              required: true,
              message: "职业/身份不能为空",
            },
          ],
        },

        // {
        //   mode: "time",
        //   label: "报名时间",
        //   prop: "runStartTime",
        //   inputConfig: {
        //     "value-format": "hh:mm:ss",
        //   },
        //   rules: [
        //     {
        //       type: "string",
        //       required: true,
        //       message: "报名时间不能为空",
        //     },
        //   ],
        // },
        {
          mode: "select",
          label: "参与比赛项目",
          minWidth: "300px",
          prop: "items",
          renderProp: "items$view",
          placeholder: "多项选择",
          // spliter:' - ',
          inputConfig: {
            clearable: true,
            multiple: true,
          },
          options: [
            { value: "0", label: "羽毛球" },
            { value: "1", label: "篮球" },
            { value: "2", label: "乒乓球" },
            { value: "3", label: "游泳" },
          ],
          rules: [
            {
              required: true,
              message: "比赛项目不能为空",
            },
          ],
        },
        {
          mode: "select",
          label: "来自地区",
          prop: "from",
          minWidth: "100px",
          renderProp: "from$view",
          placeholder: "远程搜索",
          inputConfig: {
            clearable: true,
            filterable: true,
            // remote: true,
            // "remote-method": (query) => {
            //   let options = [
            //     { label: "广州", value: "CAN" },
            //     { label: "北京", value: "PEK" },
            //     { label: "上海", value: "SHA" },
            //     { label: "广汉", value: "GHA" },
            //   ];
            //   console.log("远程搜索", query);
            //   if (query) {
            //     this.dropDownOptions.from = options.filter((item) => ~item.label.indexOf(query));
            //   } else {
            //     this.dropDownOptions.from = [];
            //   }
            // },
          },
          // options: (row) => this.dropDownOptions.from,
          options: (row) => [
            { label: "广州", value: "CAN" },
            { label: "北京", value: "PEK" },
            { label: "上海", value: "SHA" },
            { label: "广汉", value: "GHA" },
          ],

          rules: [
            {
              required: true,
              message: "比赛项目不能为空",
            },
          ],
        },
      ],
      listData: [],
      rowButtons: [
        {
          name: "编辑",
          type: "primary",
          vIf: (row) => !row.isEdit,
          click: (ref) => {
            ref.edit();
          },
        },
        {
          name: "保存",
          type: "success",
          vIf: (row) => row.isEdit,
          click: (ref, row) => {
            console.log("保存", row);
            ref.validate((valid, fields) => {
              if (valid) {
                console.log("校验通过");
                ref.cancel();
              } else {
                console.log("校验不通过", fields);
              }
            });
          },
        },
        {
          name: "取消",
          type: "danger",
          vIf: (row) => row.isEdit,
          click: (ref) => {
            ref.cancel();
          },
        },

        {
          name: "删除",
          type: "danger",
          vIf: (row) => !row.isEdit,
          disabled(row, index) {
            return row.name === "ryan";
          },
          click: (ref, row, index) => {
            ref.delete();
          },
        },
        // {
        //   name: "查看",
        //   type: "success",
        //   click: (ref, row, index) => { },
        // },
      ],
    };
  },
  created() {
    this.getDropDownOptions();
    this.getList();
  },
  methods: {
    getDropDownOptions() {
      setTimeout(async () => {
        this.dropDownOptions.job = await Promise.resolve([
          { label: "运动员", value: "0" },
          { label: "工程师", value: "1" },
          { label: "学生", value: "2" },
        ]);
      }, 500);
    },
    getList() {
      fetch("../../../mock/list.json")
        .then((res) => res.json())
        .then((res) => {
          this.listData = [...res.data];
        });
    },
    handleSelectionChange(selections) {
      console.log("selections", selections);
      this.selections = selections;
    },
    activateAllRows() {
      this.$refs.ryEditTable.activateAllRows();
    },
    // 清空全部校验信息
    clearValidate() {
      this.$refs.ryEditTable.clearValidate();
    },
    // 还原全部
    recoverAll() {
      this.$refs.ryEditTable.recover();
    },
    // 插入新增行
    insert() {
      this.$refs.ryEditTable.insert({
        name: "muji",
        age: "11",
        job: "",
        date: "",
        items: [],
      });
    },
    // 保存全部
    save() {
      const { validateAll, getData, deactivateAll } = this.$refs.ryEditTable;
      validateAll((valid, err) => {
        if (valid) {
          deactivateAll();
          console.log("批量保存验证通过");
          console.log("全部数据", getData());
        } else {
          console.log("批量保存验证失败", err);
          console.log("全部数据", getData());
        }
      });
    },
    changeRules() {
      this.$refs.ryEditTable.changeRules("age", (rule, check) => {
        console.log("rule", rule);
        rule[0] = {
          type: "string",
          asyncValidator: (rule, value) => {
            return new Promise((resolve, reject) => {
              if (value > 18) {
                reject("年龄需要18岁或以下"); // reject 这个 error message
              } else {
                resolve();
              }
            });
          },
        };
        check();
      });
    },
    clearValidateByCell() {
      this.$refs.ryEditTable.clearValidateByField(this.rowIndex, this.cellProp);
    },
    bachDelete() {
      let pkids = this.selections.map((it) => it.pkid);
      this.listData = this.listData.filter((item) => !pkids.includes(item.pkid));
      console.log("this.listData : ", this.listData);
    },
    shuffleListConfig() {
      this.listConfig = shuffleArray(this.listConfig);
      console.log(this.listConfig);
    },
  },
};
</script>

<style scoped></style>
